package com.qf.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.qf.config.AlipayConfig;
import com.qf.pojo.*;
import com.qf.service.OrderService;
import com.qf.service.impl.OrderServiceImpl;
import com.qf.utils.UUIDUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 *订单的后端接口地址
 */
@WebServlet("/order")
public class OrderServlet extends BaseServlet {

    /**
     * 产生的订单功能
     * @param request 请求对象
     * @param response 响应对象
     */
    public void generateOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //0)从request获取HttpSession
        HttpSession session = request.getSession();
        //从session获取User信息
        User user = (User) session.getAttribute("user");
        if (user == null) {
            //请求转发到登录页面
            request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
            return;
        }

        //1)封装订单实体
        Order order = new Order();
        //订单编号
        order.setOid(UUIDUtils.getId());
        //下订单时间
        order.setOrdertime(new Date());

        //订单总金额total---从购物车获取
        //从HttpSession会话对象中获取Cart
        Cart cart = (Cart) session.getAttribute("cart");
        order.setTotal(cart.getTotalMoney());
        //订单支付状态state默认0
        order.setAddress("南窑国际");
        order.setName(user.getName());
        order.setTelephone(user.getTelephone());
        //封装user新
        order.setUser(user);
        //封装里包很多订单项的数据items--List<OrderItem>
        //需要封装这个item数据---->需要订单项OrderItem---->封装商品的数量/商品/小计金额---->来自于购物车项
        //购物车中获取所有的购物车项的信息
        //声明订单项实体
        OrderItem orderItem = null;
        for (CartItem cartItem : cart.getBeans()) {
            //封装多个定个订单项
            orderItem = new OrderItem();
            //封装订单项的编号
            orderItem.setItemid(UUIDUtils.getId());
            //count/product/subtotal---来自于购物车项
            orderItem.setCount(cartItem.getCount());
            orderItem.setProduct(cartItem.getProduct());
            orderItem.setSubtotal(cartItem.getSubTotal());

            //这个订单项所属的订单
            orderItem.setOrder(order);
            //封装订单实体中的item---集合数据(存储订单项)
            List<OrderItem> listItems = order.getItems();
            listItems.add(orderItem) ;
            order.setItems(listItems);
        }


        //测试
        //System.out.println(order);

        //2)调用订单业务接口
        OrderService orderService = new OrderServiceImpl() ;
        orderService.addOrder(order) ;


        //3)将订单实体存在request域中
        request.setAttribute("order",order) ;
        //请求转发到/jsp/order_info.jsp
        request.getRequestDispatcher("/jsp/order_info.jsp").forward(request,response);
    }


    /**
     * 订单支付
     * @param request 请求
     * @param response 响应
     */
    public void orderPay(HttpServletRequest request,HttpServletResponse response){
        //接收表单提交过来的隐藏域里面的 订单编号
        String oid = request.getParameter("oid");

        //调用订单业务接口,通过订单编号获取指定的订单实体
        OrderService orderService = new OrderServiceImpl() ;
        Order order = orderService.getOrderByOid(oid);

        //支付宝的代码 设置订单总金额,订单的编号,主题信息...
        try {

            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(
                    //获取支付宝的网关
                    AlipayConfig.gatewayUrl,
                    //自己账户id号
                    AlipayConfig.app_id,
                    //密钥信息 :应用私钥
                    AlipayConfig.merchant_private_key,
                    //通过支付宝网关请求支付宝数据格式 "json"
                    "json",
                    //字符编码格式
                    AlipayConfig.charset,
                    //支付宝公钥
                    AlipayConfig.alipay_public_key,
                    //签名方式
                    AlipayConfig.sign_type);

            //设置请求参数
            //支付宝的支付请求对象
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

            String subject = null ;
            List<OrderItem> items = order.getItems();
            for(OrderItem orderItem :items){
                if(orderItem.getOrder().getOid().equals(order.getOid())){
                   subject = orderItem.getProduct().getPname() ;
                }
            }

            //设置支付宝的请求参数                                //设置支付的订单编号
            alipayRequest.setBizContent("{\"out_trade_no\":\""+ order.getOid() +"\","
                    //支付的总金额
                    + "\"total_amount\":\""+ order.getTotal() +"\","
                    //支付的标题
                    + "\"subject\":\""+ "数码产品" +"\","
                    + "\"body\":\""+ subject+"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

//			//商户订单号，商户网站订单系统中唯一订单号，必填
//			String out_trade_no = "asdfgre13243245335345";
//			//付款金额，必填
//			String total_amount = "1";
//			//订单名称，必填
//			String subject = "充值话费";
//			//商品描述，可空
//			String body = "话费充值1元";
//
//			alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
//					+ "\"total_amount\":\""+ total_amount +"\","
//					+ "\"subject\":\""+ subject +"\","
//					+ "\"body\":\""+ body +"\","
//					+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
            //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
            //		+ "\"total_amount\":\""+ total_amount +"\","
            //		+ "\"subject\":\""+ subject +"\","
            //		+ "\"body\":\""+ body +"\","
            //		+ "\"timeout_express\":\"10m\","
            //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

            //请求
            //响应一个支付宝的登录页面
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            //输出
            System.out.println(result);

            response.getWriter().write(result); //直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }


}
